<?php

/**
 * Abstraction pour les classes prenant en charge les requetes SQL
 *
 * @category   McCube
 * @package    Db
 * @author     Leiha Sellier <leiha.sellier@gmail.com>
 * @license    http://creativecommons.org/licenses/by/3.0/  CC BY 3.0
 * @link       http://code.google.com/p/mechanics-cubes/
 */
abstract class McCube_Db_Query{

    protected $_query     = '';
    protected $_table     = '';
    protected $_fields    = array();
    protected $_values    = array();
    protected $_orderBy   = '';
    protected $_limit     = '';
    protected $_where     = '';
    protected $_database  = null;
    protected $_maxItemInResult = '';

    abstract public function build();

    public function __construct($database){
        $this->_database = $database;
    }

    public function exec(&$count=0){
        return $this->_database->exec($this->build(), $count);
    }

    public function table($table){
        if(!empty($this->_table))
            $this->_table .= ' , ';

        $this->_table = $table;
        return $this;
    }

    public function orderBy($field, $order=null){
        if($order)
            $field .= ' '.$order;

         if(!empty($this->_orderBy))
            $this->_orderBy .= ' , ';

        $this->_orderBy .= $field;
        return $this;
    }

    public function limit($nbLimit, $start=0){
        if($start > 0)
            $this->_limit = $start.' , ';

        $this->_limit .= $nbLimit;
        $this->_maxItemInResult = $nbLimit;
        return $this;
    }

    public function mustHaveSingleRow(){
        return $this->_maxItemInResult === 1;
    }

    public function where($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_where .= $this->__($expression, $value, $valueType);
        return $this;
    }

    public function andWhere($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_where .= ' AND ('.$this->__($expression, $value, $valueType).')';
        return $this;
    }

    public function orWhere($expression, $value=null, $valueType=PDO::PARAM_STR){
        $this->_where .= ' OR ('.$this->__($expression, $value, $valueType).')';
        return $this;
    }

    protected function __($expression, $value=null, $valueType=PDO::PARAM_STR){
        return $expression
            .(!is_null($value) ? ' '.$this->_database->quote($value, $valueType)  : '')
        ;
    }

    protected function _getPDOConstantType($var){
      if(is_int ($var)) return PDO::PARAM_INT;
      if(is_bool($var)) return PDO::PARAM_BOOL;
      if(is_null($var)) return PDO::PARAM_NULL;
      return PDO::PARAM_STR;
    }
}